<?php

namespace app\index\controller;

use think\Controller;
use think\Request;
use app\index\model\User as userModel;
use think\Db;
use Firebase\JWT\JWT;
class User extends Controller
{
	protected $beforeActionList=[
		'cu' => ["except"=>"login"]
	];
	public function cu(){
		// checkUser();
	}
    public function login(){
		$name = input('post.name');
		$password = input('post.password');
		$user = Db::query('select * from user where name=?',[$name]);
		// $user = Db::table('user')->where('name',$name)->find();
		// return json($user);
		if($user){
			if($password==$user[0]['password']){
				$key = 'example_key';
				$payload = array(
				    'iss' => 'http://example.org',
				    'aud' => 'http://example.com',
				    'iat' => time(),
				    'nbf' => time(),
					'exp' => time()+3600,
					'data'=> $name
				);
				$jwt = JWT::encode($payload, $key, 'HS256');
				$res = ["code"=>200,"data"=>$jwt];
				return json($res);
			}else{
				return json("{code:'401',msg:'密码错误'}");
			}
		}else{
			return json("{code:'401',msg:'用户不存在'}");
		}
	}
    public function save()
    {
        //
		$name = input('post.name');
		$password = input('post.password');
		$user = new userModel();
		$user->name = $name;
		$user->password = $password;
		$user->save();
    }

    public function update()
    {
        //
		$name = input('post.name');
		$password = input('post.password');
		$id = input('post.id');
		$user = userModel::get($id);
		if($name){
			$user->name = $name;
		}
		if($password){
			$user->password = $password;
		}
		$user->save();
    }
 //    public function select(){
	// 	$user = Db::query('select * from user');
	// 	return json($user);
	// } 
    public function query()
    {
        //
		$id = input('get.id');
		// $user = userModel::get($id);
		// $role = $user->roles;
		$user = Db::query('select name as permissionName,b.rolename from permission pe right join 
		(select rp.permissionId,ur.rolename from rolePermission rp left join
		(select name as rolename,a.roleId from roles left join 
		(select roleId from user_role where userId=?) a 
		on a.roleId=roles.id) ur 
		on ur.roleId=rp.roleId) b
		on pe.id=b.permissionId',[$id]);
		return json($user);
    }
	public function queryAll()
	{
	    //
		$user = Db::query('select uname,group_concat(rolename) as roleName,group_concat(name) as permissionName from permission right join
		(select permissionId,rolename,uname from rolePermission right join
		(select name as rolename,uname,r.roleId from roles right join 
		(select roleId,uname from user_role right join
		(select id,name as uname from user) u
		on u.id= user_role.userId) r
		on roles.id=r.roleId) as ur
		on ur.roleId=rolePermission.roleId) urp
		on urp.permissionId=permission.id group by uname');
		return json($user);
	}
	public function select(){
		$users = userModel::select();
		return json($users);
	}
    public function delete()
    {
        //
		$id = input('get.id');
		$user = userModel::get($id);
		$user->delete();
    }
}
